package com.meizhuang.controller;


import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class RSAEncrypt {

	private static PrivateKey privateKey;

	public static PrivateKey getPrivateKey(String filename) throws IOException {
		try {
			InputStream in = new ClassPathResource(filename).getInputStream();
			byte[] data = new byte[1024];
			int len;
			String content = "";
			while((len=in.read(data))!=-1){
				content += new String(data,0,len);
			}
			in.close();

			String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
					.replace("-----END PRIVATE KEY-----", "")
					.replaceAll("\\s+", "");

			KeyFactory kf = KeyFactory.getInstance("RSA");
			RSAEncrypt.privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
			return RSAEncrypt.privateKey;
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("当前Java环境不支持RSA", e);
		} catch (InvalidKeySpecException e) {
			throw new RuntimeException("无效的密钥格式");
		}
	}

	public static PrivateKey getPrivateKey() throws IOException {
		if (null == privateKey) {
			String fileName = "apiclient_key.pem";
			privateKey = getPrivateKey(fileName);

			return privateKey;
		}

		return privateKey;
	}
}